package start.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 过滤器  主要控制用户登录才能访问 以及登陆超时
 */
@Configuration
@Slf4j
public class FilterConfig {

    @Autowired
    StringRedisTemplate redisTemplate;


    @Bean
    public Filter getFilter() { //返回一个过滤器
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

                response.setContentType("text/html;charset=utf-8");
                String url = request.getRequestURL().toString();
                System.out.println("FilterUrl:"+url);

               int n = url.indexOf("sms/sendSms");// 验证码路径

                int m = url.indexOf("getRoleToChenkedMenu") ;
                if (url.indexOf("login") > 0 || url.indexOf("getOrgList")>0 || url.indexOf("getMenuMethod")>0 ||m>0 ||n>0) {
                    chain.doFilter(request, response);//如果是登录请求,让请求通过
                }else {

                    String key = request.getParameter("token");//查看会话ID

                    if (key == null || key.equals("")) { //1.前端没有携带会话id
                        response.getWriter().write("{\"resultCode\":\"110\",\"text\":\"请求被拒绝,请勿非法访问\"}");
                        log.info("{\"resultCode\":\"110\",\"text\":\"请求被拒绝,请勿非法访问\"}");
                    } else {                               //前端携带会话id
//                        String token_val = redisTemplate.opsForValue().get(key);   //值为 用户id
                        String token_val = redisTemplate.opsForValue().get(key);


                        if(token_val==null){    // 会话过期
                            response.getWriter().write("{\"resultCode\":\"120\",\"text\":\"请求超时，请重新登录\"}");

                            log.info("{\"resultCode\":\"120\",\"text\":\"请求超时，请重新登录\"}");
                        }else{

                            redisTemplate.boundHashOps(key).expire(30*60, TimeUnit.SECONDS);
                            chain.doFilter(request,response);
                        }

                    }
                }
            }

        };
        }
    }

